package com.hwy.catering.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwy.catering.dto.DishDto;
import com.hwy.catering.entity.Category;
import com.hwy.catering.entity.Dish;
import com.hwy.catering.entity.MealDetail;
import com.hwy.catering.entity.User;
import com.hwy.catering.mapper.CategoryMapper;
import com.hwy.catering.mapper.DishMapper;
import com.hwy.catering.mapper.MealDetailMapper;
import com.hwy.catering.service.DishService;
import com.hwy.catering.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Resource
    private DishMapper dishMapper;

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private MealDetailMapper mealDetailMapper;

    @Override
    public R findDishOptions() {
        //最终返回的数据
        ArrayList<Object> finalList = new ArrayList<>();
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getType,1);
        //查询菜品类别
        List<Category> categoryList = categoryMapper.selectList(wrapper);
        //根据菜品类别id，去查询该类别的所有菜品
        for (Category category : categoryList) {
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("value",category.getId().toString());
            hashMap.put("label",category.getName());
            ArrayList<Map> list = new ArrayList<>();
            LambdaQueryWrapper<Dish> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(Dish::getCategoryId, category.getId().toString());
            //查出某类的所有菜品
            List<Dish> dishList = dishMapper.selectList(wrapper1);
            for (Dish dish: dishList) {
                HashMap<Object, Object> map = new HashMap<>();
                map.put("value",dish.getId().toString());
                map.put("label",dish.getName());
                list.add(map);
            }
            hashMap.put("children",list);
            finalList.add(hashMap);
        }
        return R.success(finalList);
    }

    @Override
    public R exportDish(HttpServletResponse response) {
        try {
            //设置下载信息
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码
            String fileName = URLEncoder.encode("菜品信息", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

            //查询所有用户信息
            List<Dish> dishList = dishMapper.selectList(null);
            /**
             * easyexcel，默认是支持Date日期格式的导出的，但是不支持LocalDateTime日期格式，所以报错：
             *        com.alibaba.excel.exception.ExcelDataConvertException: Can not find 'Converter' support class LocalDateTime.
             * 解决方法:自定义LocalDateStringConverter
             */
            //EasyExcel写操作
            EasyExcel.write(response.getOutputStream(), Dish.class)
                    .sheet("菜品信息")
                    .doWrite(dishList);
            System.out.println("user导出xlsx成功");
        }catch(Exception e) {
            System.out.println("user导出xlsx失败.");
        }
        return R.success("成功导出");
    }

    @Override
    @Transactional
    public R deleteSelect(List<Dish> dishList) {
        for (Dish dish:dishList){
            LambdaQueryWrapper<MealDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(MealDetail::getDishId,dish.getId());
            Integer integer = mealDetailMapper.selectCount(wrapper);
            if (integer != 0) {
                return R.error("该菜品和套餐关联了，无法删除。");
            }
            dishMapper.deleteById(dish.getId());
        }
        return R.success("删除成功");
    }

    @Override
    public R deletedDish(Long id) {
        //查看该类别是否与套餐关联
        LambdaQueryWrapper<MealDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MealDetail::getDishId,id);
        Integer integer = mealDetailMapper.selectCount(wrapper);
        if (integer != 0) {
            return R.error("该菜品和套餐关联了，无法删除。");
        }
        int i = dishMapper.deleteById(id);
//        System.out.println("删除结果："+i);
        return R.success("删除菜品成功。");
    }

    @Override
    public R editDish(Long id, Dish dish) {
        dish.setId(id);
        int i = dishMapper.updateById(dish);
        System.out.println("更改结果："+i);
        return R.success("更改成功。");
    }

    @Override
    public R getByIdDish(Long id) {
        Dish dish = dishMapper.selectById(id);
        return R.success(dish);
    }

    @Override
    public R addDish(Dish dish) {
        System.out.println(dish.getTag());
        int insert = dishMapper.insert(dish);
        System.out.println("添加菜品结果："+insert);
        return R.success("添加菜品成功。");
    }

    @Override
    public R findDish(Page<Dish> pageParam,Dish dish) {
        HashMap<Object, Object> map = new HashMap<>();
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        if ( dish.getName() != null && !dish.getName().trim().isEmpty()) {
            wrapper.eq("name",dish.getName());
        } else if (dish.getCategoryId() != null ) {
            wrapper.eq("category_id",dish.getCategoryId());
        }
        Page<Dish> page = page(pageParam,wrapper);
        List<Dish> dishes = page.getRecords();
        ArrayList<DishDto> list = new ArrayList<>();
        for (Dish dish1 : dishes){
            DishDto dishDto = new DishDto();
            Category category = categoryMapper.selectById(dish1.getCategoryId());
            String name1 = category.getName();
            //用类别id拿到类别名称，存入dishDto中
            BeanUtil.copyProperties(dish1,dishDto);
            dishDto.setCategoryName(name1);
            list.add(dishDto);
        }
        map.put("page",page);
        map.put("dishData",list);
        return R.success(map);
    }
}
